package com.coder.oj.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.oj.admin.mapstruct.AnswerMapstruct;
import com.coder.oj.admin.query.AnswerQuery;
import com.coder.oj.admin.service.AnswerService;
import com.coder.oj.admin.vo.AnswerVo;
import com.coder.oj.common.core.JsonPage;
import com.coder.oj.common.core.JwtToken;
import com.coder.oj.common.core.R;
import com.coder.oj.common.entity.Answer;
import com.coder.oj.common.entity.Discuss;
import com.coder.oj.common.enums.CommonStatusEnum;
import com.coder.oj.common.mapper.AnswerMapper;
import com.coder.oj.common.mapper.DiscussMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Api(tags = {"题解管理"})
@RestController
@RequestMapping("/answer")
public class AnswerController {

    @Autowired
    private AnswerService answerService;

    @Autowired
    private AnswerMapper answerMapper;

    @Autowired
    private AnswerMapstruct answerMapstruct;

    @JwtToken
    @PostMapping("/page")
    @ApiOperation("分页查询")
    public R<JsonPage<AnswerVo>> getAnswerPage(@RequestBody AnswerQuery params) {
        return R.ok().setResult(answerService.getAnswerPage(params));
    }

    @JwtToken
    @GetMapping
    @ApiOperation("题解详情")
    public R<AnswerVo> getAnswerById(@RequestParam("id") Long id) {
        return R.ok().setResult(answerMapstruct.toVO(answerMapper.selectById(id)));
    }

    @JwtToken
    @PutMapping("/status")
    @ApiOperation("修改题解状态")
    @Transactional(rollbackFor = Exception.class)
    public R deleteAnswerById(@RequestParam("id") Long id) {
        Answer answer = answerMapper.selectById(id);
        if(ObjectUtils.isEmpty(answer)) {
            return R.ok();
        }
        answer.setStatus(
                CommonStatusEnum.getEnum(answer.getStatus()) == CommonStatusEnum.ENABLED ?
                        CommonStatusEnum.DISABLED.getValue() : CommonStatusEnum.ENABLED.getValue());
        answerMapper.updateById(answer);
        return R.ok();
    }
}
